package com.itheima.config;

import com.itheima.pojo.ActiveUser;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (activeUser.getRoleList()!=null&&activeUser.getRoleList().size()>0){
            for (Role role : activeUser.getRoleList()) {
                info.addRole(role.getRolename());
            }
        }
        if (activeUser.getPermissionList()!=null&&activeUser.getPermissionList().size()>0){
            for (Permission permission : activeUser.getPermissionList()) {
                info.addStringPermission(permission.getPercode());
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        ActiveUser activeUsers = userService.queryUserByName(username);
        if (activeUsers!=null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUsers,activeUsers.getUser().getUserpwd(), ByteSource.Util.bytes(activeUsers.getUser().getAddress()),this.getName());
            return info;
        }else {
            return null;
        }
    }
}
